using LiJ.Http.Mos;
using LiJ.Pay.WeiXin.Cash.Mos;
using LiJ.Pay.WeiXin.SysTools;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;

namespace LiJ.Pay.WeiXin.Cash
{
	public class WxPayRedApi : WxPayBaseApi
	{
		/// <summary>
		/// 构造函数
		/// </summary>
		/// <param name="config"></param>
		public WxPayRedApi(WxPayCenterConfig config = null)
			: base(config)
		{
		}

		/// <summary>
		///  发送普通红包
		/// </summary>
		/// <param name="redReq"></param>
		/// <returns></returns>
		public async Task<WxPaySendRedResp> SendRedPackageAsync(WxPaySendRedReq redReq)
		{
			string addressUrl = "https://api.mch.weixin.qq.com" + "/mmpaymkttransfers/sendredpack";
			return await this.SendRedPackageAsync<WxPaySendRedResp>(addressUrl, redReq.GetDics());
		}

		/// <summary>
		///  发送裂变红包
		/// </summary>
		/// <param name="redReq"></param>
		/// <returns></returns>
		public async Task<WxPaySendRedResp> SendGroupRedPackageAsync(WxPaySendGroupRedReq redReq)
		{
			string addressUrl = "https://api.mch.weixin.qq.com" + "/mmpaymkttransfers/sendgroupredpack";
			return await this.SendRedPackageAsync<WxPaySendRedResp>(addressUrl, redReq.GetDics());
		}

		/// <summary>
		///   post 支付接口相关请求
		/// </summary>
		/// <typeparam name="T">返回参数类型</typeparam>
		/// <param name="addressUrl">接口地址</param>
		/// <param name="xmlDirs">请求参数的排序字典（不包括：appid,mch_id,sign。 会自动补充）</param>
		/// <returns></returns>
		private async Task<T> SendRedPackageAsync<T>(string addressUrl, SortedDictionary<string, object> xmlDirs) where T : WxPayBaseResp, new()
		{
			xmlDirs.Add("wxappid", (object)base.ApiConfig.AppId);
			xmlDirs.Add("mch_id", (object)base.ApiConfig.MchId);
			base.CompleteDicSign(xmlDirs);
			LHttpRequest LHttpRequest = new LHttpRequest();
			LHttpRequest.HttpMothed = HttpMothed.Post;
			LHttpRequest.AddressUrl = addressUrl;
			LHttpRequest.CustomBody = xmlDirs.ProduceXml();
			return await base.RestCommonAsync<T>(LHttpRequest, (Func<HttpResponseMessage, Task<T>>)null, base.GetCertHttpClient());
		}

		/// <summary>
		///  查询红包
		/// </summary>
		/// <param name="mch_billno">商户订单号</param>
		/// <param name="bill_type">订单类型</param>
		/// <returns></returns>
		public async Task<WxPayQueryRedResp> QueryRedAsync(string mch_billno, string bill_type = "MCHT")
		{
			string addressUrl = "https://api.mch.weixin.qq.com" + "/mmpaymkttransfers/gethbinfo";
			SortedDictionary<string, object> xmlDirs = new SortedDictionary<string, object>
			{
				["nonce_str"] = SysUtil.GenerateNonceStr(),
				["mch_billno"] = mch_billno,
				["bill_type"] = bill_type
			};
			return await base.PostApiAsync(addressUrl, xmlDirs, (Func<HttpResponseMessage, Task<WxPayQueryRedResp>>)null, base.GetCertHttpClient(), (Action<SortedDictionary<string, object>>)null);
		}
	}
}
